<?php


namespace App\Http\Middleware;

use App\Model\User;
use App\Model\WeappToken;
use App\Tool\Annotation;
use App\Tool\Json;
use Closure;
use Nette\Reflection\ClassType;

class CheckWeappToken
{

    /**
     * 验证前端用户token
     * Create by Peter
     * 2019/08/27 17:13:12
     * Email:904801074@qq.com
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \ReflectionException
     */
    public function handle($request, Closure $next)
    {

        $token=$request->header('token')??null;


        $data=Annotation::getAnnotationByRoute('Weapp');

        //跳过验证
        if($data['type']=='no_check') return $next($request);

        if(!$token) return response()->json(Json::codeArray(10, 'token不存在！'));


        $now=time();


        $data=WeappToken::with('user')->where('token',$token)->first();


        if(!$data) return response()->json(Json::codeArray(11, 'token未找到！'));


        $expire_time=$data->expire_time;


        if($now>$expire_time) return response()->json(Json::codeArray(12, 'token已过期！333'));

        app()->instance('weapp_user',$data->user->toArray());

        return $next($request);

    }

}
